'use strict'

let util = require('util');
let fs = require('fs');
let models = require('../modules/models');
let Fiber = require('fibers');

let studentService = require('../modules/services/student');
let checkTimeSetService = require('../modules/services/checktimeset');
let userService = require('../modules/services/user');

let School = models.School;
let Classroom = models.Classroom;
let Grade = models.Grade;
let NatureClass = models.NatureClass;
let Student = models.Student;
let FestivalTip = models.FestivalTip;
let Festival = models.Festival;
let Teacher = models.Teacher;
let Attendance = models.Attendance;
let AttendanceValue = models.AttendanceValue;
let AttendanceStatus = models.AttendanceStatus;
let Track = models.Track;
let TrackType = models.TrackType;

let SchoolDao = models.SchoolDao;
let ClassroomDao = models.ClassroomDao;
let GradeDao = models.GradeDao;
let NatureClassDao = models.NatureClassDao;
let StudentDao = models.StudentDao;
let UserDao = models.UserDao;
let CardDao = models.CardDao;
let CheckTimeSetDao = models.CheckTimeSetDao;
let CheckTimeDao = models.CheckTimeDao;
let FestivalTipDao = models.FestivalTipDao;
let FestivalDao = models.FestivalDao;
let TeacherDao = models.TeacherDao;
let AttendanceDao = models.AttendanceDao;
let AttendanceValueDao = models.AttendanceValueDao;
let TrackDao = models.TrackDao;

function createModels(modelType, modelDao, data) {
    modelDao.remove({});

    let models = data.map(datum => new modelType(datum));
    models.forEach(model => modelDao.create(model));

    return models;
}

function createModelsNoDelete(modelType, modelDao, data) {
    let models = data.map(datum => new modelType(datum));
    models.forEach(model => modelDao.create(model));

    return models;
}

function createSchool(classrooms, grades, festivals) {
    return createModels(School, SchoolDao, [{
            name: '合肥168中学',
            classrooms: [
                classrooms[0],
                classrooms[1]
            ],
            grades: [
                grades[0]
            ],
            checkTimeSet: checkTimeSetService.createInstance(),
            festivals: festivals
        }, {
            name: '合肥市第四十二中学',
            classrooms: [
                classrooms[2],
                classrooms[3]
            ],
            grades: [
                grades[1]
            ],
            checkTimeSet: checkTimeSetService.createInstance()
        }, {
            name: '合肥市绿怡小学',
            classrooms: [
                classrooms[4],
                classrooms[5]
            ],
            grades: [
                grades[2],
                grades[3]
            ],
            checkTimeSet: checkTimeSetService.createInstance()
        }
    ]);
}

function createClassroom() {
    return createModels(Classroom, ClassroomDao, [{
        name: '高一（1）班'
    }, {
        name: '高一（27）班'
    }, {
        name: '七（1）班'
    }, {
        name: '七（12）班'
    }, {
        name: '二（2）班'
    }, {
        name: '三（5）班'
    }]);
}

function createGrades(natureClasses) {
    return createModels(Grade, GradeDao, [{
        name: '高一',
        natureClasses: [
            natureClasses[0],
            natureClasses[1]
        ],
        checkTimeSet: checkTimeSetService.createInstance()
    }, {
        name: '七年级',
        natureClasses: [
            natureClasses[2],
            natureClasses[3]
        ],
        checkTimeSet: checkTimeSetService.createInstance()
    }, {
        name: '二年级',
        natureClasses: [
            natureClasses[4]
        ],
        checkTimeSet: checkTimeSetService.createInstance()
    }, {
        name: '三年级',
        natureClasses: [
            natureClasses[5]
        ],
        checkTimeSet: checkTimeSetService.createInstance()
    }]);
}

function createNatureClass(studentData) {
    return createModels(NatureClass, NatureClassDao, [{
        name: '高一（1）班',
        students: studentData['合肥168中学']['高一（1）班'].students
    }, {
        name: '高一（27）班',
        students: studentData['合肥168中学']['高一（27）班'].students
    }, {
        name: '七（1）班',
        students: studentData['合肥市第四十二中学']['七（1）班'].students
    }, {
        name: '七（12）班',
        students: studentData['合肥市第四十二中学']['七（12）班'].students
    }, {
        name: '二（2）班',
        students: studentData['合肥市绿怡小学']['二（2）班'].students
    }, {
        name: '三（5）班',
        students: studentData['合肥市绿怡小学']['三（5）班'].students
    }]);
}

function generateAttendanceValue(candidation) {
    let index = Math.floor(Math.random() * candidation.length);

    return candidation[index];
}

function createStudents(studentData) {
    Object.keys(studentData).forEach(schoolName => {
        let classList = Object.keys(studentData[schoolName]);
        classList.forEach(className => {
            let csvFilePath = util.format('utils/data/%s/%s/list.csv', schoolName, className);
            let csvFileContent = fs.readFileSync(csvFilePath).toString();
            let students = studentService.fromCsvData(csvFileContent);
            students.forEach(student => StudentDao.create(student));
            studentData[schoolName][className].students = students;

            // 全部设置为空
            let today = new Date();
            today.setHours(0);
            today.setMinutes(0);
            today.setSeconds(0);
            for ( let dayIndex = 0; dayIndex < 7; dayIndex ++ ) {
                students.forEach(student => {
                    let attendance = new Attendance({
                        student: student,
                        date: today,
                        values: [
                            new AttendanceValue({
                                enterStatus: AttendanceStatus.Created,
                                exitStatus: AttendanceStatus.Created
                            }),
                            new AttendanceValue({
                                enterStatus: AttendanceStatus.Created,
                                exitStatus: AttendanceStatus.Created
                            }),
                            new AttendanceValue({
                                enterStatus: AttendanceStatus.Created,
                                exitStatus: AttendanceStatus.Created
                            })
                        ]
                    });

                    attendance.values.forEach(value => AttendanceValueDao.create(value));
                    AttendanceDao.create(attendance);
                });

                today = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
            }
        });
    });

    return studentData;
}

function createFestival() {
    return createModels(Festival, FestivalDao, [{
        name: '清明节',
        start: new Date('Sat Apr 02 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Mon Apr 04 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }, {
        name: '劳动节',
        start: new Date('Sat Apr 30 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Mon May 02 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }, {
        name: '国庆节',
        start: new Date('Sat Oct 01 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Fri Oct 07 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }]);
}

function createFestivalTip() {
    return createModels(FestivalTip, FestivalTipDao, [{
        name: '清明节',
        start: new Date('Sat Apr 02 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Mon Apr 04 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }, {
        name: '劳动节',
        start: new Date('Sat Apr 30 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Mon May 02 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }, {
        name: '国庆节',
        start: new Date('Sat Oct 01 2016 00:00:00 GMT+0800 (CST)'),
        end: new Date('Fri Oct 07 2016 24:00:00 GMT+0800 (CST)'),
        status: 1
    }]);
}

function createTeacher(schools, grades, natureClasses) {
    return createModels(Teacher, TeacherDao, [{
        tid: '0003',
        name: '张三',
        managedClasses: [ natureClasses[0] ],
        user: userService.createUserOfRole('0003', 'e10adc3949ba59abbe56e057f20f883e', 'teacher')
    }, {
        tid: '0002',
        name: '李四',
        managedGrade: grades[0],
        user: userService.createUserOfRole('0002', 'e10adc3949ba59abbe56e057f20f883e', 'grade_manager')
    }, {
        tid: '0001',
        name: '王五',
        managedSchool: schools[0],
        user: userService.createUserOfRole('0001', 'e10adc3949ba59abbe56e057f20f883e', 'leader')
    }, {
        tid: '0011',
        name: '耿中',
        managedSchool: schools[2],
        user: userService.createUserOfRole('0011', 'e10adc3949ba59abbe56e057f20f883e', 'leader')
    }, {
        tid: '0013',
        name: '耿正',
        managedClasses: [ natureClasses[4], natureClasses[5] ],
        user: userService.createUserOfRole('0013', 'e10adc3949ba59abbe56e057f20f883e', 'teacher')
    }]);
}

function createTimeToday(hour, minute, second) {
    let time = new Date();

    time.setHours(hour);
    time.setMinutes(minute);
    time.setSeconds(second);

    return time;
}

function createTracks(classrooms) {
    TrackDao.remove({});

    ['120150000', '120150001', '120150002', '120150003'].forEach(sid => {
        let student = StudentDao.findOne({
            sid: sid
        });

        return createModelsNoDelete(Track, TrackDao, [{
            student: student,
            time: createTimeToday(13, 50, 0),
            type: TrackType.EnterSchool
        }, {
            student: student,
            time: createTimeToday(13, 55, 0),
            type: TrackType.EnterClassroom,
            classroom: classrooms[0]
        }, {
            student: student,
            time: createTimeToday(16, 10, 0),
            type: TrackType.ExitClassroom,
            classroom: classrooms[0]
        }, {
            student: student,
            time: createTimeToday(16, 15, 0),
            type: TrackType.EnterClassroom,
            classroom: classrooms[1]
        }, {
            student: student,
            time: createTimeToday(16, 30, 0),
            type: TrackType.ExitClassroom,
            classroom: classrooms[1]
        }, {
            student: student,
            time: createTimeToday(16, 45, 0),
            type: TrackType.ExitSchool
        }]);
    });
}

let StudentData = {
    '合肥168中学': {
        '高一（1）班': {},
        '高一（27）班': {}
    },
    '合肥市第四十二中学': { 
        '七（1）班': {}, 
        '七（12）班': {} 
    },
    '合肥市绿怡小学': { 
        '二（2）班': {}, 
        '三（5）班': {} 
    }
};

Fiber(function() {
    UserDao.remove({});
    CardDao.remove({});
    StudentDao.remove({});
    CheckTimeSetDao.remove({});
    CheckTimeDao.remove({});
    FestivalDao.remove({});
    AttendanceDao.remove({});
    AttendanceValueDao.remove({});

    let studentData = createStudents(StudentData);
    let natureClasses = createNatureClass(studentData);
    let grades = createGrades(natureClasses);
    let classrooms = createClassroom();
    let festivals = createFestival();
    let festivalTips = createFestivalTip();
    let schools = createSchool(classrooms, grades, festivals);
    let teachers = createTeacher(schools, grades, natureClasses);
    let tracks = createTracks(classrooms);
    
    process.exit();
}).run();

